package org.kl.bf.service.basic;

import java.util.List;
import java.util.Map;

import org.kl.bf.entity.basic.DocumentContent;
import org.kl.bf.repository.basic.DocumentContentDao;
import org.kl.bf.utils.CRUDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;


//Spring Bean的标识.
@Component
//默认将类中的所有public函数纳入事务管理.
@Transactional
public class DocumentContentService {
	
	private DocumentContentDao documentContentDao;

	public DocumentContent getDocumentContent(String guid) {
		return documentContentDao.findOne(guid);
	}
	
	public DocumentContent getDCByHelpDocId(String helpDocId){
		return documentContentDao.findByHelpDocId(helpDocId);
	}

	public void saveDocumentContent(DocumentContent entity) {
		documentContentDao.save(entity);
	}

	public void deleteDocumentContent(String guid) {
		documentContentDao.delete(guid);
	}
	
	public void delJoinFileId(String joinFileId){
		DocumentContent documentContent = documentContentDao.findByJoinFileId(joinFileId);
		documentContent.setJoinFileId("");
		documentContentDao.save(documentContent);
	}

	public List<DocumentContent> getAllDocumentContent() {
		return (List<DocumentContent>)documentContentDao.findAll();
	}

	public Page<DocumentContent> getUserDocumentContent(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<DocumentContent> spec = buildSpecification(searchParams);

		return documentContentDao.findAll(spec, pageRequest);
	}
	
	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<DocumentContent> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<DocumentContent> spec = DynamicSpecifications.bySearchFilter(filters.values(), DocumentContent.class);
		return spec;
	}

	@Autowired
	public void setDocumentContentDao(DocumentContentDao documentContentDao) {
		this.documentContentDao = documentContentDao;
	}

}
